<template>
	<view class="agent-join-container">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-arrow">←</text>
			</view>
			<view class="header-title">
				<text>代理加盟申请</text>
			</view>
		</view>

		<!-- 主内容 -->
		<view class="main-content-status" v-if="type==1">
			<img src="/static/images/img.jpg" mode="aspectFill" class="banner-image"></img>
			<!-- 价格与购买按钮 -->
			<view class="price-section">
				<view class="price-text">¥8999加盟代理</view>
				<button class="buy-button" @click="buyProduct">立即购买</button>
			</view>
		</view>
		<view class="main-content" v-else>
			<view class="form-section">
				<!-- 用户名输入 -->
				<view class="form-item">
					<text class="label">用户名</text>
					<input class="input" type="text" v-model="formData.name" placeholder="请输入您的姓名" />
				</view>

				<!-- 手机号输入 -->
				<view class="form-item">
					<text class="label">手机号</text>
					<input class="input" type="tel" v-model="formData.mobile" placeholder="请输入您的手机号" maxlength="11" />
				</view>


				<!-- 申请按钮 -->
				<button class="apply-button" @click="handleApply">提交申请</button>

				<!-- 申请说明 -->
				<view class="apply-note">
					<text>提交申请后，工作人员将与您联系确认并办理相关手续</text>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		agentAPI
	} from '../../utils/api.js'
	import { invokeWechatPay, handlePaymentResult, getDefaultPaymentParams } from '../../utils/payment.js'
	export default {
		data() {
			return {
				// 表单数据
				type: 1,
				formData: {
					name: '',
					mobile: ''
				}
			}
		},

		onLoad() {
			// 页面加载时的逻辑
		},

		methods: {
			async buyProduct() {
				const ua = window.navigator.userAgent.toLowerCase()
				this.isWechatEnv = ua.indexOf('micromessenger') > -1

				uni.showLoading({
				  title: '处理中...'
				})
				
				try {
				  // 准备支付参数
				  const params = getDefaultPaymentParams({
				    productId: 1
				  })
				  const response = await agentAPI.agentBuy(params)
				  // 处理支付结果
				  const paymentResult = handlePaymentResult(response)
				  
				  if (paymentResult.success) {
				    const payData = this.isWechatEnv?paymentResult.data.order.jsApi?.params:paymentResult.data.order
				    
				    console.log('支付数据:', payData.payURL)
				    
				    // 如果是微信环境，并且返回了微信支付所需参数，调用微信支付
				    if (this.isWechatEnv&&payData.timeStamp && payData.nonceStr && payData.package && payData.paySign) {
				      try {
				        // 调起微信支付
				        await invokeWechatPay(payData, (res) => {
				          console.log('微信支付成功:', res)
				          uni.showToast({
				            title: '支付成功',
				            icon: 'success'
				          })
				          uni.setStorageSync('isMember',1)
				          // 支付成功后延迟返回上一页
				          setTimeout(() => {
				            uni.navigateBack()
				          }, 1500)
				        })
				      } catch (wechatError) {
				        console.error('微信支付失败:', wechatError)
				        uni.showToast({
				          title: wechatError.message || '微信支付失败，请重试',
				          icon: 'none'
				        })
				      }
				    } else if (payData.payURL) {
				      // 非微信环境，或者没有返回微信支付参数，跳转到支付URL
				      console.log('跳转到支付页面:', payData.payURL)
				      window.location.href = payData.payURL
				    } else {
				      // 其他情况，提示用户
					  console.log('支付请求成功，请按照提示完成支付:', payData)
				      
				      // 延迟返回上一页
				      setTimeout(() => {
				        uni.navigateBack()
				      }, 1500)
				    }
				  } else {
				    // 支付请求失败
				    console.error('支付请求失败:', paymentResult.message)
				    uni.showToast({
				      title: paymentResult.message || '支付请求失败，请重试',
				      icon: 'none'
				    })
				  }
				} catch (error) {
				  console.error('支付异常:', error)
				  uni.showToast({
				    title: '支付过程中出现异常，请重试',
				    icon: 'none'
				  })
				} finally {
				  uni.hideLoading()
				}
			},
			// 返回上一页
			goBack() {
				if (this.type == 1) {
					uni.navigateBack()
				} else {
					this.type = 1
				}

			},

			// 表单验证
			validateForm() {
				if (!this.formData.name.trim()) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.mobile.trim()) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return false
				}

				// 简单的手机号格式验证
				const phoneReg = /^1[3-9]\d{9}$/
				if (!phoneReg.test(this.formData.mobile)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return false
				}

				return true
			},

			// 处理申请提交
			async handleApply() {
				// 表单验证
				if (!this.validateForm()) {
					return
				}

				try {
					// 显示加载提示
					uni.showLoading({
						title: '提交中...'
					})

					// 调用代理商申请接口
					const result = await agentAPI.agentApply(this.formData)

					// 隐藏加载提示
					uni.hideLoading()

					// 处理响应结果
					if (result.code === 0) {
						uni.showToast({
							title: '申请提交成功',
							icon: 'success'
						})

						// 申请成功后延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: result.message || '申请提交失败，请重试',
							icon: 'none'
						})
					}
				} catch (error) {
					// 隐藏加载提示
					uni.hideLoading()

					console.error('代理商申请失败:', error)
					uni.showToast({
						title: '网络错误，请检查网络连接后重试',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.header {
		background-color: #4A4062;
		padding: 10px 15px 10px 15px;
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
		z-index: 100;
		width: 100%;
	}

	.back-btn {
		position: relative;
		z-index: 7;
		width: 40px;
		height: 40px;
		background-color: rgba(240, 217, 181, 0.1);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10px;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.back-btn:active {
		background-color: rgba(240, 217, 181, 0.2);
		transform: scale(0.95);
	}

	.back-arrow {
		color: #F0D9B5;
		font-size: 22px;
		font-weight: bold;
	}

	.header-title {
		flex: 1;
		text-align: center;
		position: absolute;
		left: 0;
		right: 0;
	}

	.header-title text {
		color: #F0D9B5;
		font-size: 20px;
		font-weight: bold;
	}

	.agent-join-container {
		background-color: #1F1630;
		min-height: 100vh;
		position: relative;
		overflow: hidden;
	}

	.main-content {
		padding: 80px 20px 20px;
		position: relative;
		z-index: 2;
	}

	.main-content-status {
		position: relative;
		width: 100%;
	}

	.banner-image {
		width: 100%;
	}

	.form-section {
		width: 100%;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.label {
		display: block;
		color: #FFFFFF;
		font-size: 16px;
		margin-bottom: 8px;
		font-weight: 500;
	}

	.input {
		width: 100%;
		height: 44px;
		background-color: rgba(255, 255, 255, 0.1);
		border: 1px solid rgba(240, 217, 181, 0.2);
		border-radius: 8px;
		padding: 0 15px;
		font-size: 16px;
		color: #FFFFFF;
		box-sizing: border-box;
	}

	.input::placeholder {
		color: rgba(255, 255, 255, 0.4);
	}

	.price-info {
		text-align: center;
		margin: 30px 0;
	}

	.price-text {
		color: #F0D9B5;
		font-size: 18px;
		font-weight: bold;
	}

	.apply-button {
		width: 100%;
		height: 48px;
		line-height: 48px;
		background-color: #4A4062;
		color: #F0D9B5;
		border: none;
		border-radius: 24px;
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.apply-button:active {
		background-color: #3A3052;
	}

	.apply-note {
		text-align: center;
		padding: 0 10px;
	}

	.apply-note text {
		color: rgba(255, 255, 255, 0.5);
		font-size: 14px;
		line-height: 1.5;
	}

	/* 适配不同尺寸的屏幕 */
	@media screen and (max-width: 375px) {
		.main-content {
			padding: 70px 15px 15px;
		}

		.header-title text {
			font-size: 18px;
		}

		.apply-button {
			height: 44px;
			font-size: 16px;
		}

		.garland-container {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 1;
			width: 100%;
			display: flex;
			justify-content: space-between;
			padding: 0 80rpx;
		}
	}

	.garland-image {
		width: 120rpx;
		height: 120rpx;
		opacity: 0.8;
	}

	.agent-card {
		position: relative;
		width: 400rpx;
		height: 400rpx;
		margin-bottom: 60rpx;
		animation: float 3s ease-in-out infinite;
	}

	@keyframes float {

		0%,
		100% {
			transform: translateY(0px);
		}

		50% {
			transform: translateY(-20rpx);
		}
	}

	.card-image {
		width: 100%;
		height: 100%;
	}

	.card-badge {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		background-color: #F44336;
		padding: 10rpx 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.badge-text {
		color: #FFFFFF;
		font-size: 28rpx;
		font-weight: bold;
	}

	.advantages-section {
		text-align: center;
		margin-bottom: 60rpx;
	}

	.advantage-text {
		display: block;
		font-size: 36rpx;
		color: #FFFFFF;
		margin-bottom: 10rpx;
	}

	.features-grid {
		display: flex;
		justify-content: space-between;
		width: 80%;
		margin-bottom: 80rpx;
	}

	.feature-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.feature-icon {
		width: 100rpx;
		height: 100rpx;
		background-color: #3A3052;
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
	}

	.feature-icon image {
		width: 60rpx;
		height: 60rpx;
	}

	.price-section {
		position: fixed;
		left: 0;
		bottom: 0;
		color: #fff;
		font-size: 18px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		box-sizing: border-box;
		padding: 10px 30px;
		background-color: #4A4062;
	}

	.price-text {
		color: #F0D9B5;
		font-size: 40rpx;
		font-weight: bold;
		margin-right: 40rpx;
	}

	.buy-button {
		box-sizing: border-box;
		background-color: #F44336;
		color: #FFFFFF;
		font-size: 32rpx;
		font-weight: bold;
		padding: 5rpx 40rpx;
		border-radius: 40px;
		border: none;
		margin: 0;
		box-shadow: 0 4rpx 12rpx rgba(244, 67, 54, 0.4);
	}

	.buy-button:active {
		transform: scale(0.95);
		opacity: 0.9;
	}

	.bottom-nav {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background-color: #2A2240;
		display: flex;
		justify-content: space-around;
		align-items: center;
		border-top: 1rpx solid #3A3052;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #8F82A8;
	}

	.nav-item.active {
		color: #F0D9B5;
	}

	.nav-item image {
		width: 50rpx;
		height: 50rpx;
		margin-bottom: 10rpx;
	}

	.nav-item text {
		font-size: 24rpx;
	}
</style>